from flask import request

from owl_ai.application.knowledge_base_app_service import KnowledgeBaseAppService
from owl_ai.domain.knowledge.knowledge_service import KnowledgeService, KnowledgeFileService
from owl_ai.domain.model.knowledge_entity import KnowledgeBaseEntity
from owl_common.base.model import AjaxResponse
from owl_common.descriptor.serializer import JsonSerializer
from owl_common.descriptor.validator import BodyValidator
from ... import reg


@reg.api.route("/ai/knowledgebase/create", methods=["POST"])
@BodyValidator()
@JsonSerializer()
def create_knowledge_base(dto: KnowledgeBaseEntity):
    """
    创建知识库
    """
    knowledge_base_id = KnowledgeService.insert(dto)
    return AjaxResponse.from_success(data=knowledge_base_id)


@reg.api.route("/knowledge/list", methods=["GET"])
@JsonSerializer()
def get_knowledge_base_list():
    """
    获取知识库列表
    """
    knowledge_list = KnowledgeService.list()
    return AjaxResponse.from_success(data=knowledge_list)


@reg.app.route("/knowledge/detail/<int:knowledge_base_id>", methods=["GET"])
@JsonSerializer()
def get_knowledge_base_detail(knowledge_base_id):
    """
    获取知识库详情
    """

    knowledge_file_list = KnowledgeBaseAppService.knowledge_file_list(knowledge_base_id)

    return AjaxResponse.from_success(data=[{
        "docId": knowledge_file.id,
        "docName": knowledge_file.file_name,
        "docType": knowledge_file.file_type,
    } for knowledge_file in knowledge_file_list])


@reg.app.route("/knowledge/attach/upload", methods=["POST"])
@JsonSerializer()
def knowledge_attach_upload():
    kid = request.form.get("kid")
    file = request.files.get("file")

    ret = KnowledgeBaseAppService.upload(kid, file)

    return AjaxResponse.from_success(data=ret)


@reg.app.route("/knowledge/similarity_search", methods=["POST"])
@JsonSerializer()
def similarity_search():
    """
    语义搜索
    """
    kid = request.values.get("kid")
    query = request.values.get("query")
    size = request.values.get("size")
    ret = KnowledgeBaseAppService.similarity_search(kid, query, size)
    return AjaxResponse.from_success(data=ret)
